#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/1 14:39
# @Author  : 王凯
# @File    : henan_jzsbaxrmzf_adc0_policy.py
# @Project : scrapy_spider
import json
import re

import scrapy

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class henan_jzsbaxrmzf_adc0_policy(BaseTaxPolicySpider):
    name = "henan_jzsbaxrmzf_adc0_policy"
    province: str = "河南省"  # 取表格
    city: str = "焦作市"  # 取表格
    county: str = "博爱县"  # 取表格
    park: str = ""  # 取表格
    source: str = "焦作市博爱县人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.boai.gov.cn/viewCmsCac.do?cacId=ff8080817b965a85017c34ae1a9e096e"  # 注明入口网址，以便后续排错

    def start_requests(self):
        url = 'http://www.boai.gov.cn/viewCmsCac.do?cacId=ff8080817ca79f9c017d454941d33076&offset=0'
        yield scrapy.Request(url, callback=self.parse_page)

    def parse_page(self, response, **kwargs):
        yield from self.parse_list(response, **kwargs)
        page_num = int(response.xpath('.').re_first(r"共(\d+)页"))
        for i in range(1, page_num + 1):
            new_url = f'http://www.boai.gov.cn/viewCmsCac.do?cacId=ff8080817ca79f9c017d454941d33076&offset={15 * i}'
            yield scrapy.Request(new_url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        for url in response.xpath('//*[@class="colRightOne"]//a/@href').extract():
            yield response.follow(url, callback=self.parse_detail)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get("item") is None else response.meta.get("item")
        item["title"] = response.xpath("""string(//title)""").get()
        item["publish_date"] = response.xpath("""string(.)""").re_first(r"发?\s*[布文]?\s*[日时]\s*[期间]\s*[:：]+\s*([\w\W]{1,500}?)\s+")
        item["content"] = response.xpath(""".""").get()
        item["province"] = self.province
        item["city"] = self.city
        item["county"] = self.county
        item["park"] = self.park
        item["source"] = self.source
        item["source_url"] = response.request.url
        if item["publish_date"]:
            yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_jzsbaxrmzf_adc0_policy".split())
